<?php

namespace app\common\model;

use think\Model;
use think\Validate;

class Tag extends Model
{

    /**
     * 添加标签
     *
     * @param $post
     *
     * @return array
     */
    public function add($post)
    {
        $validate = new Validate([
            'name|标签名称' => 'require',
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }

        try {
            $this->save(['name' => $post['name']]);
        } catch (\Exception  $e) {
            return ['code' => 0, 'message' => $e->getMessage()];
        }
        return ['code' => 1, 'message' => '标签添加成功'];
    }

    /**
     * 标签标签
     *
     * @param $post
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($post)
    {
        $validate = new Validate([
            'id|标签id' => 'require',
            'name|标签名称' => 'require',
        ]);
        if (!$validate->check($post)) {
            return ['code' => 0, 'message' => $validate->getError()];
        }
        $res = $this->find($post['id']);
        $res->save([
            'name' => $post['name'],
        ]);
        return ['code' => 1, 'message' => '标签修改成功'];
    }
}
